package com.xoa.service.party;

import com.xoa.dao.party.MapOwnerinfoMapper;
import com.xoa.model.party.trashMiniature;
import com.xoa.util.ToJson;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.beans.Transient;
import java.io.File;
import java.io.InputStream;
import java.util.*;

@Service
public class TrashMiniatureService {
    @Autowired
    private com.xoa.dao.party.trashMiniatureMapper trashMiniatureMapper;
    @Autowired
    private MapOwnerinfoMapper mapOwnerinfoMapper;

    public ToJson trminBySelect(){

        ToJson json=new ToJson();
        try {
            List<trashMiniature> list=trashMiniatureMapper.trminBySelect();

            json.setFlag(0);
            json.setObj(list);
            json.setMsg("ok");
            return json;
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询
     * @param page
     * @param pageSize
     * @param mid
     * @return
     */
    public ToJson trminSelect(Integer page, Integer pageSize, Integer mid, boolean useFlag, String codeNo){
        Map<String,Object> map=new HashMap<String,Object>();
        ToJson json=new ToJson();
        page=(page-1)*pageSize;
        map.put("page",page);
        map.put("pageSize",pageSize);
        map.put("mid",mid);
        map.put("codeNo",codeNo);
        try {
            List<trashMiniature> list=trashMiniatureMapper.trminSelect(map);
            int taol=trashMiniatureMapper.trmcount(map);
            json.setObject(taol);
            json.setFlag(0);
            json.setObj(list);
            json.setMsg("ok");
            return json;
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }



    public ToJson trminSelectList(Integer page, Integer pageSize, Integer mid, boolean useFlag, trashMiniature trashMiniature){
        Map<String,Object> map=new HashMap<String,Object>();
        ToJson json=new ToJson();
        page=(page-1)*pageSize;
        map.put("page",page);
        map.put("pageSize",pageSize);
        map.put("mid",mid);
        map.put("trashMiniature",trashMiniature);
        try {
            List<com.xoa.model.party.trashMiniature> list=trashMiniatureMapper.trminSelectList(map);

            String jutiAddress=mapOwnerinfoMapper.selectByLabelName(list.get(0).getGridLocation());

            list.get(0).setJutiAddress(jutiAddress);

            int taol=trashMiniatureMapper.trmcount(map);
            json.setObject(taol);
            json.setFlag(0);
            json.setObj(list);
            json.setMsg("ok");
            return json;
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 删除
     * @param mid
     * @return
     */
    public ToJson delete(Integer mid){
        ToJson json=new ToJson();
        try{
            int count=trashMiniatureMapper.deleteByPrimaryKey(mid);
            if(count>0){
                json.setMsg("ok");
                json.setFlag(0);
                return json;
            }
            json.setMsg("删除失败");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 修改
     * @param
     * @return
     */
    @Transient
    public ToJson update(trashMiniature trashMiniature){
        ToJson json=new ToJson();
        try{
            int count=trashMiniatureMapper.updateByPrimaryKey(trashMiniature);
            if(count>0){
                json.setMsg("ok");
                json.setFlag(0);
                return json;
            }
            json.setMsg("修改失败");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 添加
     */
    @Transient
    public ToJson add(trashMiniature trashMiniature){
        ToJson json=new ToJson();
        try{
            int count=trashMiniatureMapper.insert(trashMiniature);
            if(count>0){
                json.setMsg("ok");
                json.setFlag(0);
                return json;
            }
            json.setMsg("添加失败");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    public ToJson ecoudInsert(MultipartFile file){
        int count=0;//計數器
        ToJson json=new ToJson();
        try{
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            }else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");//判读当前系统
                    //读取配置文件
                    ResourceBundle rb = ResourceBundle.getBundle("upload");
                    String osName = System.getProperty("os.name");
                    StringBuffer path = new StringBuffer();
                    if (osName.toLowerCase().startsWith("win")) {
                        path = path.append(rb.getString("upload.win"));
                    } else {
                        path = path.append(rb.getString("upload.linux"));
                    }
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
//                    // 将文件上传成功后进行读取文件
//                    // 进行读取的路径
//                    String readPath = path.append(newFileName).toString();
//                    InputStream in = new FileInputStream(readPath);
                    InputStream in =  file.getInputStream();

                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    trashMiniature trashMiniature = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        trashMiniature = new trashMiniature();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //所属社区
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            trashMiniature.setGridId(Integer.valueOf(cell.getStringCellValue()));
                                            break;
                                        case 1:
                                            //位置
                                            trashMiniature.setTdw(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //用户ID
                                            trashMiniature.setUserId(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 3:
                                            //tel
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            trashMiniature.setTel(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //备注
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            trashMiniature.setEizbhu(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 5:
                                            //坐标
                                            trashMiniature.setGridLocation(mapOwnerinfoMapper.selectCoordingbyName(cell.getStringCellValue()));
                                            break;
                                        default:
                                            json.setFlag(0);
                                            json.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            //将数据放入数据库
                            if(trashMiniature!=null && trashMiniature.getGridId()!=null){
                                int count1=trashMiniatureMapper.insertSelective(trashMiniature);
                                if(count1>0) {
                                    count += count1;
                                }
                                dest.delete();
                            }
                        }
                    }

                }
            }
            if(count>0){
                json.setTotleNum(count);
                json.setMsg("ok");
                json.setFlag(0);
                return  json;
            }
        }catch (Exception e){
            json.setMsg("err");
            e.printStackTrace();
        }finally {
            return json;
        }
    }
}
